package com.feonix.common.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Base64.Encoder;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 密码加密算法
 * @author Administrator
 *
 */
public class MD5Util {
	
	protected final static Log logger = LogFactory.getLog(MD5Util.class);

	private final static String salt = "!@#";

	/**
	 * md5 + base64 加密
	 * @param oldStr
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	public static String encodeMd5Base64(final String oldStr) throws NoSuchAlgorithmException{
		//确定计算方法
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		Encoder base64Encoder = Base64.getEncoder();
		String encodeStr = base64Encoder.encodeToString(md5.digest(oldStr.getBytes()));
		return encodeStr;
	}
	
	/**
	 * 带salt加密
	 * @param password
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	public static String encodePwd(final String password){
		String result = "";
		try {
			result = encodeMd5Base64(password+salt);
		} catch (Exception e) {
			logger.error("function:encodePwd() 47line error:", e);
		}
		return result;
	}
	
	/**
	 * 判断密码是否一样
	 * @param plaintext
	 * @param encodePwd
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	public static boolean checkPwd(final String plainPwd, final String encodePwd){
		return encodePwd.equals(encodePwd(plainPwd));
	}
	
	public static void main(String[] args) throws NoSuchAlgorithmException {
		System.out.println(encodePwd("feonix"));
	}
	
}
